﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Animation;

namespace LoadingControl.Control
{
	/// <summary>
	/// Thanks to http://www.brianlagunas.com/index.php/2009/08/21/a-simple-wpf-loading-animation/
	/// </summary>
	public partial class LoadingAnimation : UserControl
	{
		public LoadingAnimation()
		{
			InitializeComponent();
		}

		#region IsLoading
		public bool IsLoading
		{
			get { return (bool)GetValue(IsLoadingProperty); }
			set { SetValue(IsLoadingProperty, value); }
		}

		public static readonly DependencyProperty IsLoadingProperty = DependencyProperty.Register("IsLoading", typeof(bool), typeof(LoadingAnimation), new PropertyMetadata(IsLoadingChanged));

		private static void IsLoadingChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
		{
			var control = d as LoadingAnimation;
			if (control != null)
			{
				var storyboard = control.Resources["ProgressAnimation"] as Storyboard;
				if ((bool)e.NewValue)
				{
					storyboard.Begin();
				}
				else
				{
					//Stop animation to save CPU
					storyboard.Stop();
				}
			}
		}
		#endregion
	}
}
